<template>
  <!-- <a-drawer
    title="当前航段详情"
    placement="right"
    width="100%"
    class="fra-drawer fra-drawer-s"
    :closable="true"
    :mask="false"
    :visible="flightLegDetailsVisible"
    @close="onClose"
  > -->

  <a-modal
    :mask-closable="false"
    :visible="flightLegDetailsVisibleF"
    title="航段详情 - Flight Leg Details"
    :class="['c-dialog-box fld-main-box ',singlePage?'c-dialog-box-full':'']"
    :dialog-style="{height:'795px'}"
    :footer="null"
    :width="1210"
    :z-index="modalZIndexM"
    destroy-on-close
    :closable="!singlePage"
    centered
    @cancel="onClose"
  >
    <span slot="closeIcon" class="c-close-icon"><a-icon :component="require('@/assets/icon/close.svg')" /></span>
    <span v-if="!singlePage" class="new-page-btn" @click="goNewPageHandler(flduuid)"><a-icon :component="require('@/assets/icon/newPage.svg')" /></span>
    <a-spin :spinning="flightLegDetailLoading" class="c-dialog-search-box">
      <!-- info -->
      <a-row class="c-dialog-search-box-2">
        <a-col :span="2">
          <div class="fw-b fs-12 color-r">机号</div>
          <a class="fs-16 fw-b numbers" @click="setState({key:'flightLegHistoryVisible',payload:true})">{{ titleInfo.tailnumber ||'--' }}</a>
        </a-col>
        <a-col :span="3">
          <div class="fw-b fs-12 color-r">机队</div>
          <div class="fs-16 fw-b color-title numbers">{{ titleInfo.fleet||'--' }}</div>
        </a-col>
        <a-col :span="2">
          <div class="fw-b fs-12 color-r">航班</div>
          <div class="fs-16 fw-b color-title numbers">{{ titleInfo.flightNo||'--' }}</div>
        </a-col>
        <a-col :span="2">
          <div class="fw-b fs-12 color-r">航段</div>

          <div class="fs-16 fw-b color-title numbers">{{ $legHandler(flightLegDetailData.leg,currentRow.totalLeg) }}</div>
        </a-col>
        <a-col :span="5">
          <div class="fw-b fs-12 color-r">机场</div>
          <div class="fs-16 fw-b color-title">
            <a @click="airportInfoHandler(titleInfo.dep)">{{ titleInfo.dep ||'--' }}</a>
            <span class="c-arrow color-s">····</span>
            <a @click="airportInfoHandler(titleInfo.arr)">{{ titleInfo.arr ||'--' }}</a>
          </div>
        </a-col>
        <a-col :span="4">
          <div class="fw-b fs-12 color-r">日期</div>
          <div class="fw-b fs-16 color-title">{{ titleInfo.outTime?$moment.utc(titleInfo.outTime).format('YYYY-MM-DD HH:mm') :'--' }}</div>
        </a-col>
        <a-col :span="4">
          <div class="fw-b fs-12 color-r">预计到达</div>
          <div class="fw-b fs-13">
            <span class="fs-16 color-title fw-b">{{ titleInfo.eta? $moment.utc(titleInfo.eta).format('YYYY-MM-DD HH:mm') :'--' }}</span>
          </div>

        </a-col>
      </a-row>
    </a-spin>
    <a-spin :spinning="flightLegDetailLoading" class="c-dialog-search-box-t">
      <a-collapse
        v-model="activeKey"
        :bordered="false"
        :expand-icon="expandICon"
        expand-icon-position="right"
        class="fld-top-title"
        @change="changeActiveHandler"
      >
        <a-collapse-panel key="1" header="展开飞行详情">
          <a-row :gutter="38">
            <!-- 飞行详情 -->
            <a-col :span="17">
              <a-descriptions layout="vertical" :column="4" class="fld-l">
                <span slot="title" class="fld-title">
                  飞行详情
                </span>
                <a-descriptions-item>
                  <span slot="label" class="fw-500 fld-title">OUT</span>
                  <div class="text-color-505363">{{ flightLegDetailData.outTime?$moment.utc(flightLegDetailData.outTime).format('YYYY-MM-DD HH:mm') :'--' }}</div>
                  <div class="mt-10 fw-b text-color-505363 numbers">{{ $numberFormat(flightLegDetailData.outFuel) }} Ibs</div>
                </a-descriptions-item>
                <a-descriptions-item>
                  <span slot="label" class="fw-500 fld-title">OFF</span>
                  <div class="text-color-505363">{{ flightLegDetailData.offTime?$moment.utc(flightLegDetailData.offTime).format('YYYY-MM-DD HH:mm') :'--' }}</div>
                  <div class="mt-10 fw-b text-color-505363 numbers">{{ $numberFormat(flightLegDetailData.offFuel) }} Ibs</div>
                </a-descriptions-item>
                <a-descriptions-item>
                  <span slot="label" class="fw-500 fld-title">ON</span>
                  <div class="text-color-505363">{{ flightLegDetailData.onTime?$moment.utc(flightLegDetailData.onTime).format('YYYY-MM-DD HH:mm') :'--' }}</div>
                  <div class="mt-10 fw-b text-color-505363 numbers">{{ $numberFormat(flightLegDetailData.onFuel) }} Ibs</div>
                </a-descriptions-item>
                <a-descriptions-item>
                  <span slot="label" class="fw-500 fld-title">IN</span>
                  <div class="text-color-505363">{{ flightLegDetailData.inTime?$moment.utc(flightLegDetailData.inTime).format('YYYY-MM-DD HH:mm') :'--' }}</div>
                  <div class="mt-10 fw-b text-color-505363 numbers">{{ $numberFormat(flightLegDetailData.inFuel) }} Ibs</div>
                </a-descriptions-item>
              </a-descriptions>
              <!-- 油况概况 -->
              <h3 class="mb-10 fld-title fs-14 fw-b">油耗概况</h3>
              <a-table
                class="oil-cndition-box text-color-21252e fs-12"
                size="small"
                bordered
                :columns="columns"
                :data-source="tableData"
                :row-key="(row,index) =>row.t1"
                :pagination="false"
              />
            </a-col>

            <!-- 航班详情 -->
            <a-col :span="6" class="fld-r">
              <a-descriptions :column="1">
                <span slot="title" class="fld-title">
                  航班详情
                </span>
                <a-descriptions-item>
                  <span slot="label" class="fw-b fs-14 text-color-21252E">航空公司</span>
                  <div class="fs-14 text-color-9ea5b2">{{ flightLegDetailData.airline }}</div>
                </a-descriptions-item>
                <a-descriptions-item>
                  <span slot="label" class="fw-b text-color-21252E">机队</span>
                  <span class="fs-14 text-color-9ea5b2">{{ flightLegDetailData.fleet||'--' }}</span>
                </a-descriptions-item>
                <!-- <a-descriptions-item>
                  <span slot="label" class="fw-b text-color-21252E">g CO2 / Seat-miles</span>
                  <span class="fs-14 text-color-9ea5b2">0</span>
                </a-descriptions-item> -->
                <a-descriptions-item>
                  <span slot="label" class="fw-b text-color-21252E">Elapsed Time</span>
                  <span class="fs-14 text-color-9ea5b2">{{ flightLegDetailData.elapsedTime?
                    $moment.duration(flightLegDetailData.elapsedTime, "minutes").format("h[h]m[m]"):'--' }}</span>
                </a-descriptions-item>
                <a-descriptions-item>
                  <span slot="label" class="fw-b text-color-21252E">平均飞行时间</span>
                  <span class="fs-14 text-color-9ea5b2">{{
                    flightLegDetailData.averageFlightTime?
                      $moment.duration(flightLegDetailData.averageFlightTime, "minutes").format("h[h]m[m]"):'--' }}</span>
                </a-descriptions-item>
                <a-descriptions-item>
                  <span slot="label" class="fw-b text-color-21252E">Great Circle Distance</span>
                  <span class="fs-14 text-color-9ea5b2">{{ flightLegDetailData.greatCircleDistance||'--' }}</span>
                </a-descriptions-item>
              </a-descriptions>
            </a-col>
          </a-row>

        </a-collapse-panel>

      </a-collapse>

      <!-- 报告 -->
      <div class="pla-zw" />
      <a-collapse
        v-model="activeKey2"
        :bordered="false"
        :expand-icon="expandICon"
        expand-icon-position="right"
        class="fld-bottom-title"
      >
        <a-collapse-panel key="1" header="报告">
          <a-tag
            class="rp-type-btn"
            :class="{'rp-type-active':reportTypes.length===0}"
            @click="triggerHandler('all')"
          >
            全部
          </a-tag>

          <a-tag
            v-for="item in flightLegDetailReportTypes"
            :key="item.name"
            class="rp-type-btn"
            :class="{'rp-type-active':reportTypes.includes(item.name)}"
            @click="triggerHandler(item.name)"
          >
            {{ item.name }}
          </a-tag>
          <a-spin :spinning="flightLegDetailReportListLoading" class=" beauty-scroll">

            <a-row :gutter="12" class="width-change-box">
              <a-col :span="repShow?9:24" class="left-menu">
                <vxe-table
                  ref="xTable1"
                  class="event-trigger-packet-upload fld-vxe-table "
                  show-overflow
                  highlight-hover-row
                  row-id="id"
                  resizable
                  :row-class-name="rowVxeClassHandler"
                  :tooltip-config="{
                    enterable:true,
                  }"
                  :data="flightLegDetailReportList"
                  :height="vxeH"
                  @cell-click="customRow"
                >
                  <vxe-table-column field="reportType" title="事件类型" />
                  <!-- <vxe-table-column field="content" title="Report Content" width="128">
                    <template #default="{ row }">
                      <div>{{ row.contentTime?$moment.utc(row.contentTime).format('HH:mm'):"--" }}</div>
                      <div>{{ row.contentTime?$moment.utc(row.contentTime).format('YYYY-MM-DD'):"--" }}</div>
                    </template>
                  </vxe-table-column> -->
                  <vxe-table-column v-if="!repShow" field="sendTime" title="Airplane Transmit" width="135">
                    <template #default="{ row }">
                      <div>{{ row.sendTime?$moment.utc(row.sendTime).format('HH:mm'):"--" }}</div>
                      <div>{{ row.sendTime?$moment.utc(row.sendTime).format('YYYY-MM-DD'):"--" }}</div>
                    </template>
                  </vxe-table-column>
                  <vxe-table-column v-if="!repShow" field="providerTime" title="ACARS Provider" show-overflow width="135">
                    <template #default="{ row }">
                      <div>{{ row.providerTime?$moment.utc(row.providerTime).format('HH:mm'):"--" }}</div>
                      <div>{{ row.providerTime?$moment.utc(row.providerTime).format('YYYY-MM-DD'):"--" }}</div>
                    </template>
                  </vxe-table-column>
                  <vxe-table-column v-if="!repShow" field="receiptTime" title="ETAMS Receipt" show-overflow width="118">
                    <template #default="{ row }">
                      <div>{{ row.receiptTime?$moment.utc(row.receiptTime).format('HH:mm'):'--' }}</div>
                      <div>{{ row.receiptTime?$moment.utc(row.receiptTime).format('YYYY-MM-DD'):'--' }}</div>
                    </template>
                  </vxe-table-column>
                  <vxe-table-column v-if="!repShow" field="ahmReceiptTime" title="AHM Receipt" show-overflow width="118">
                    <template #default="{ row }">
                      <div>{{ row.ahmReceiptTime?$moment.utc(row.ahmReceiptTime).format('HH:mm'):'--' }}</div>
                      <div>{{ row.ahmReceiptTime?$moment.utc(row.ahmReceiptTime).format('YYYY-MM-DD'):'--' }}</div>
                    </template>
                  </vxe-table-column>
                  <vxe-table-column v-if="!repShow" field="providerAddress" title="orig. Provider" show-overflow width="118" />
                  <vxe-table-column v-if="!repShow" field="destAddress" title="Dest. Address" show-overflow width="120" />
                  <vxe-table-column v-if="!repShow" field="msgSeq" title="Msg Seq" show-overflow width="80" />
                  <vxe-table-column v-if="!repShow" field="version" title="Version" show-overflow width="100" />
                </vxe-table>
              </a-col>
              <dragAdjustWidth v-show="repShow" :style-loc="styleLoc" />
              <a-col v-if="repShow" :span="repShow?15:24" class="flight-leg-details-data-main-box right-menu">

                <span class="new-page-btn-report" @click="goNewPageReportHandler">
                  <a-icon :component="require('@/assets/icon/newPage.svg')" />
                </span>

                <a-tabs v-model="repTab" @change="changeTabHandler">

                  <a-tab-pane key="2" force-render>
                    <span slot="tab" class="d-flex ai-center">
                      格式化数据
                      <a-icon type="printer" class="ml-6" @click="(e)=>printerHandler(e,2)" />
                    </span>

                  </a-tab-pane>
                  <a-tab-pane key="1">
                    <span slot="tab" class="d-flex ai-center">
                      原始数据
                      <a-icon type="printer" class="ml-6" @click="(e)=>printerHandler(e,1)" />
                    </span>
                  </a-tab-pane>
                </a-tabs>
                <div v-show="repTab==='1'" class="snapshot-data-s beauty-scroll">
                  <div style="margin-top:-24px">
                    {{ repShowData.content }}
                  </div>
                </div>
                <div v-show="repTab!=='1'" class="snapshot-data-s2 beauty-scroll fld-pre-main-box">
                  <a-spin :spinning="repAnalysisJsonLoading" class="w-100" />
                  <div v-show="repShowData.smi!=='CFD'">

                    <div v-show="!repAnalysisJsonLoading&&!(htmlSourceCode==='<pre></pre>'&&(repShowData.smi==='DFD'||repShowData.smi==='ENG'))">
                      <div v-if="repAnalysisJsonTitleExist" class="format-top-table">
                        <div class="format-top-table-item">
                          <div class="format-top-table-item-th">ACID</div>
                          <div class="format-top-table-item-td">{{ repAnalysisJsonTitle['ACID']||'--' }}</div>
                        </div>
                        <div class="format-top-table-item">
                          <div class="format-top-table-item-th">FLTNO</div>
                          <div class="format-top-table-item-td">{{ repAnalysisJsonTitle['FLTNO']||'--' }}</div>
                        </div>
                        <div class="format-top-table-item format-top-table-item-33">
                          <div class="format-top-table-item-th">LEG DATE</div>
                          <div class="format-top-table-item-td">{{ repAnalysisJsonTitle['LEG DATE']?$moment.utc(repAnalysisJsonTitle['LEG DATE']).format('YYYY-MM-DD HH:mm:ss'):'--' }}</div>
                        </div>
                        <div class="format-top-table-item">
                          <div class="format-top-table-item-th">DEP</div>
                          <div class="format-top-table-item-td">{{ repAnalysisJsonTitle['DEP']||'--' }}</div>
                        </div>
                        <div class="format-top-table-item">
                          <div class="format-top-table-item-th">ARR</div>
                          <div class="format-top-table-item-td">{{ repAnalysisJsonTitle['ARR']||'--' }}</div>
                        </div>
                      </div>
                      <div v-if="repAnalysisJsonTitleExist" class="mt-8 mb-12 format-top-table">
                        <div class="format-top-table-item format-top-table-item-50">
                          <div class="format-top-table-item-th">TRANSMIT DATE</div>
                          <div class="format-top-table-item-td">{{ repAnalysisJsonTitle['TRANSMIT DATE']?$moment.utc(repAnalysisJsonTitle['TRANSMIT DATE']).format('YYYY-MM-DD HH:mm:ss'):'--' }}</div>
                        </div>
                        <div class="format-top-table-item format-top-table-item-50">
                          <div class="format-top-table-item-th">MESSAGE DATE</div>
                          <div class="format-top-table-item-td">{{ repAnalysisJsonTitle['MESSAGE DATE']?$moment.utc(repAnalysisJsonTitle['MESSAGE DATE']).format('YYYY-MM-DD HH:mm:ss'):'--' }}</div>
                        </div>

                      </div>
                         <div class="legend-box">
                            <div class="b">
                              <template v-for="(v, i) in legends_info">
                                <div :key="i">
                                  <div class="word">
                                    <span>{{ v }}</span>
                                  </div>
                                  <div
                                    class="idx"
                                    :class="{
                                      aa:
                                        repShowData.content
                                          .match(/-\s{2}\w{6}/)[0]
                                          .slice(-2)
                                          .includes(v.slice(-3, -1)) ||
                                        repShowData.content
                                          .match(/-\s{2}\w{6}/)[0]
                                          .slice(-4, -2)
                                          .includes(v.slice(-3, -1))
                                    }"
                                  >
                                    {{ i + 1 }}
                                    <div
                                      v-if="
                                        repShowData.content
                                          .match(/-\s{2}\w{6}/)[0]
                                          .slice(-2)
                                          .includes(v.slice(-3, -1))
                                      "
                                      class="time"
                                    >
                                      {{
                                        repAnalysisJsonTitle['MESSAGE DATE']
                                          ? $moment
                                            .utc(repAnalysisJsonTitle['MESSAGE DATE'])
                                            .format('HH:mm')
                                          : '--'
                                      }}
                                    </div>
                                  </div>
                                </div>
                              </template>
                            </div>
                          </div>

                      <div v-html="htmlSourceCode" />
                      <div v-html="repAnalysisJsonEnding" />
                      <iframe v-show="false" id="rep-iframe-fd" frameborder="0" />
                      <div v-show="false" v-html="repAnalysisJsonData" />
                    </div>
                    <div v-if="htmlSourceCode==='<pre></pre>'&&!repAnalysisJsonLoading&&(repShowData.smi==='DFD'||repShowData.smi==='ENG')" class="text-c">
                      <span v-if="repShowData.category==='UPLINK'">下传的报文以及格式化数据，请进入“EICAS”分组进行查阅</span>
                      <span v-else>解析异常，请联系系统管理员</span>
                    </div>
                  </div>
                  <div v-show="repShowData.smi==='CFD'">
                    <div>
                      <div class="item-details-item-box">
                        <div>{{ cfdFormat[0]?cfdFormat[0].msgType:'--' }} = Report Type</div>
                        <div>{{ cfdFormat[0]&&cfdFormat[0].partNumber?cfdFormat[0].partNumber.join('，'):'--' }} = CMC or LDI Part Number</div>
                        <div>{{ cfdFormat[0]?cfdFormat[0].computorSource:'--' }} = CMC Computer Source</div>
                      </div>
                      <div>
                        <div v-for="item in tData" :key="item.id" class="cu-pointer" @click="(e)=>clickEvent(e,item)">

                          <a-row class="item-details-item-box">
                            <a-col :span="2">
                              <noticePriorityIcon :is-etops="item.isEtops" :priority="item.priority" :msg-type="item.name" />
                              <!-- <a-icon v-if="item.isEtops" :component="require('@/assets/icon/Fleet_Status_ETOPS.svg')" style="font-size:20px!important;vertical-align: top;" /> -->
                              <!-- <priorityIcon :priority="item.priority" /> -->
                            </a-col>
                            <a-col :span="2">
                              <span class="mt-10 mr-10 fs-15 fw-b">{{ item.name }}</span>
                            </a-col>
                            <a-col :span="3">
                              <a class="fw-b">{{ item.code||'--' }}</a>
                            </a-col>
                            <a-col :span="11">
                              <a class="fw-b ">{{ item.description||'--' }}</a>
                            </a-col>
                            <a-col :span="4">
                              <div class="fs-14 fw-500">{{ item.msgTime? $moment.utc(item.msgTime).format('YYYY-MM-DD HH:mm') :'--' }}</div>
                            </a-col>
                            <a-col :span="2">
                              <div class="fw-b">{{ item.activity?activeHandler(item.activity):'--' }}</div>
                            </a-col>

                            <a-col v-for="ci in item.eventDetails" :key="ci.id" :span="24">
                              <a-row>
                                <a-col :offset="4" :span="14">
                                  <div class="fs-13 text-over">
                                    <span class="mr-10 fw-b">{{ ci.name||'--' }}</span>
                                    <a>{{ ci.code ||'--' }}</a>
                                    <span class="ml-10">{{ ci.intermittence||'--' }}{{ $isNull(ci.intermittenceNum)?'':`(${ci.intermittenceNum||'--'})` }}</span>
                                    <span class="ml-10">飞行阶段：{{ ci.phase||'--' }}</span>
                                    <div class="fs-12">{{ ci.description ||'事件名称未找到，请联系管理员' }}</div>
                                    <div class="fs-12 d-flex">
                                      <span>Detected by：</span>
                                      <div>
                                        <div v-for="dbItem in ci.detectedBy" :key="dbItem">{{ dbItem }}</div>
                                      </div>
                                    </div>
                                    <div class="fs-12 "><span class="fw-b">Fault Report Code</span>：{{ ci.frc||'--' }}</div>
                                    <div class="fs-12"><span class="fw-b">Monitor Code</span>：{{ ci.mc||'--' }}</div>
                                  </div>
                                </a-col>
                                <a-col :span="4">
                                  <div class="fs-14 fw-500">{{ ci.msgTime? $moment.utc(ci.msgTime).format('YYYY-MM-DD HH:mm') :'--' }}</div>
                                </a-col>
                                <a-col :span="2">
                                  <div class="fw-b">{{ ci.activity?activeHandler(ci.activity):'--' }}</div>
                                </a-col>
                              </a-row>
                            </a-col>

                          </a-row>
                        </div>

                        <div class="mt-16 mb-10 wgwx-title fs-14 fw-b">非关联的维护信息</div>
                        <div v-for="item in bData" :key="item.id" class="cu-pointer" @click="(e)=>clickEvent(e,item)">
                          <a-row class="item-details-item-box">
                            <a-col :span="2">
                              <noticePriorityIcon :is-etops="item.isEtops" :priority="item.priority" :msg-type="item.name" />
                            </a-col>
                            <a-col :span="22">
                              <a-row>
                                <a-col :span="2">
                                  <span class="mt-10 mr-10 fs-15 fw-b">{{ item.name }}</span>
                                </a-col>
                                <a-col :span="3">
                                  <a class="fw-b">{{ item.code||'--' }}</a>
                                </a-col>
                                <a-col :span="5">
                                  <span>{{ item.intermittence||'--' }}{{ $isNull(item.intermittenceNum)?'':`(${item.intermittenceNum||'--'})` }}</span>
                                </a-col>
                                <a-col :span="5">
                                  <span>飞行阶段：{{ item.phase||'--' }}</span>
                                </a-col>
                                <a-col :span="4" :offset="3">
                                  <div class="fs-14 fw-500">{{ item.msgTime? $moment.utc(item.msgTime).format('YYYY-MM-DD HH:mm') :'--' }}</div>
                                </a-col>
                                <a-col :span="2">
                                  <div class="fw-b">{{ item.activity?activeHandler(item.activity):'--' }}</div>
                                </a-col>
                                <a-col :span="24">
                                  <span class="fs-12 ">{{ item.description||'--' }}</span>
                                </a-col>
                                <a-col :span="24">
                                  <div class="fs-12 d-flex">
                                    <span>Detected by：</span>
                                    <div>
                                      <div v-for="dbItem in item.detectedBy" :key="dbItem">{{ dbItem }}</div>
                                    </div>
                                  </div>
                                </a-col>
                                <a-col :span="24">
                                  <div class="fs-12"><span class="fw-b">Fault Report Code</span>：{{ item.frc||'--' }}</div>
                                  <div class="fs-12"><span class="fw-b">Monitor Code</span>：{{ item.mc||'--' }}</div>
                                </a-col>
                                <a-col v-for="ci in item.eventDetails" :key="ci.id" :span="24">
                                  <a-row>
                                    <a-col :offset="2" :span="16 ">
                                      <div class="fs-13 text-over">
                                        <span class="mr-10 fw-b">{{ ci.name||'--' }}</span><a>{{ ci.code ||'--' }}</a>
                                        <div>{{ ci.description ||'--' }}</div>
                                      </div>
                                    </a-col>
                                    <a-col :span="4">
                                      <div class="fs-14 fw-500">{{ ci.msgTime? $moment.utc(ci.msgTime).format('YYYY-MM-DD HH:mm') :'--' }}</div>
                                    </a-col>
                                    <a-col :span="2">
                                      <div class="fw-b">{{ ci.activity?activeHandler(ci.activity):'--' }}</div>
                                    </a-col>
                                  </a-row>
                                </a-col>

                              </a-row>
                            </a-col>
                          </a-row>

                        </div>

                      </div>

                    </div>

                  </div>
                </div>

              </a-col>
            </a-row>
          </a-spin>
        </a-collapse-panel>
      </a-collapse>
    </a-spin>
  </a-modal>
  <!-- </a-drawer> -->
</template>
<script>

import { mapState, mapActions, mapGetters, mapMutations } from 'vuex';
import { toJSON, toHTML } from '@/utils/htmlParser';
import dragAdjustWidth from '@/pages/components/dragAdjustWidth';
import { debounce } from '@/utils/util';
export default {
  components: {
    dragAdjustWidth
  },
  props: {
    // currentRow: {
    //   type: Object,
    //   default: () => {}
    // },
    flightLegDetailsVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      legends_info: [
        'Power On (PO)',
        'Engine Start (ES)',
        'Taxi Out (TA)',
        'Takeoff Roll (TO)',
        'lnitial Climb (IC)',
        'Climb (CL)',
        'Cruise (ER)',
        'Descent (DC)',
        'Approach (AP)',
        'Go Around (GA)',
        'Flare (FL)',
        'Rollout (RO)',
        'Taxi In (TI)',
        'Engine Shutdown (SD)',
        'Maintenance (MT)'
      ],
      styleLoc: {
        box: 'width-change-box',
        left: 'left-menu',
        right: 'right-menu'
      },
      modalZIndexM: 2000,
      repTab: '2',
      repId: -1,
      repShow: false,
      repShowData: {},
      vxeH: '499px',
      activeIndex: [-1],
      currentRow: {},
      activeKey: ['1'],
      activeKey2: ['1'],
      htmlSourceCode: '',
      columns: [
        {
          title: '',
          dataIndex: 't1',
          customRender: (value) => {
            return <span class='fw-500 text-color-21252e fs-12'>{value}</span>;
          }
        },
        {
          title: 'Taxi Out (Out-Off)',
          dataIndex: 't2',
          customRender: (value, record) => {
            const key = record.flag;
            return [

              <span class='fs-12 text-color-505363'>
                {this.fuels?.[key]?.taxiOut < 0 ? '(' : this.fuels?.[key]?.taxiOut ?? '--'}
              </span>
            ];
          }
        },
        {
          title: 'Flight (Off-On)',
          dataIndex: 't3',
          customRender: (value, record) => {
            const key = record.flag;
            return <span class='fs-12 text-color-505363'>{this.fuels?.[key]?.flight ?? '--'}</span>;
          }
        },
        {
          title: 'Taxi In (On-In)',
          dataIndex: 't4',
          customRender: (value, record) => {
            const key = record.flag;
            return <span class='fs-12 text-color-505363'>{this.fuels?.[key]?.taxiIn ?? '--'}</span>;
          }
        },
        {
          title: 'Block (Out-In)',
          dataIndex: 't5',
          customRender: (value, record) => {
            const key = record.flag;
            return <span class='fs-12 text-color-505363'>{this.fuels?.[key]?.block ?? '--'}</span>;
          }
        }
      ],
      tableData: [
        { t1: 'Current Sector (bs)', t2: '--', t3: '--', t4: '--', t5: '--', flag: 'currentSector' },
        { t1: 'Sector Means (lbs)', t2: '--', t3: '--', t4: '--', t5: '--', flag: 'sectorMeans' },
        { t1: 'Current Sector (lbs/hour)', t2: '--', t3: '--', t4: '--', t5: '--', flag: 'currentSectorHour' },
        { t1: 'Sector Means (lbs/hour)', t2: '--', t3: '--', t4: '--', t5: '--', flag: 'sectorMeansHour' }
      ],

      reportTypes: [],
      flduuid: ''
    };
  },
  computed: {
    ...mapState('fraMonitoring', [
      'flightLegDetailLoading',
      'flightLegDetailData',
      'flightLegDetailReportList',
      'flightLegDetailReportTypes',
      'flightLegDetailReportListNum',
      'flightLegDetailReportListLoading',
      'repAnalysisJsonData',
      'repAnalysisJsonEnding',
      'repAnalysisJsonTitle',
      'repAnalysisJsonLoading',
      'modalZIndex',
      'cfdFormat'
    ]),

    ...mapGetters('fraMonitoring', [
      'flightLegDetailsVisibleF'
    ]),
    tData() {
      return this.cfdFormat.filter(item => {
        return item.name !== 'MMSG' && !(item.name === 'Alert' || item.eventType === 'Alert' || item.msgType === 'Alert') && item.code;
      });
    },
    bData() {
      return this.cfdFormat.filter(item => item.name === 'MMSG' && item.code);
    },
    // alertData() {
    //   return this.cfdFormat.filter(item => {
    //     return (item.name === 'Alert' || item.eventType === 'Alert' || item.msgType === 'Alert') && item.code;
    //   });
    // },
    repAnalysisJsonTitleExist() {
      return Object.values(this.repAnalysisJsonTitle).length > 0;
    },
    titleInfo() {
      return Object.values(this.flightLegDetailData).length === 0 ? this.currentRow : this.flightLegDetailData;
    },
    fuels() {
      return this.flightLegDetailData?.fuels ?? {};
    },
    singlePage() {
      return ((this.$route.meta?.singlePage ?? false) && this.$route.query.rp === 'flightLegDetailsVisible');
    },
    averageFlightTime() {
      return this.$moment.duration(this.flightLegDetailData.averageFlightTime, 'minutes').format('HH\hmm:ss');
    }
  },
  watch: {
    'flightLegDetailsVisibleF': {
      handler(nv) {
        if (nv) {
          this.setState({ key: 'modalZIndex', payload: this.modalZIndex + 1 });
          this.modalZIndexM = this.modalZIndex;
          this.repShow = false;
          this.activeKey = [];
          this.activeKey2 = ['1'];

          this.flduuid = this.$route?.query?.flduuid ?? new Date().getTime();
          const lsRow = sessionStorage.getItem(`fld${this.flduuid}`) ?? localStorage.getItem('scRow') ?? localStorage.getItem('row');
          this.currentRow = JSON.parse(lsRow) ?? {};

          if (this.$store.state.setting.openType === '_blank' && !this.$route?.query?.flduuid) {
            this.goNewPageHandler(this.flduuid);
            this.setState({ key: 'flightLegDetailsVisible', payload: false });
          } else {
            this.getData();
            this.$nextTick(() => {
              const fldh = document.querySelector('.fld-top-title').clientHeight;
              this.vxeH = this.singlePage ? `${document.body.clientHeight - 92 - fldh - 150}px` : '499px';
            });
          }
        } else {
          if (nv === false && this.$store.state.setting.openType !== '_blank') {
            localStorage.removeItem('scRow');
          }

          this.vxeH = '499px';
        }
      },
      immediate: true
    }

  },
  methods: {
    ...mapActions('fraMonitoring', [
      'getFlightLegDetail',
      'getRepReportS',
      'repAnalysisJson',
      'getFormattedMessage'
    ]),
    ...mapMutations('fraMonitoring', [
      'setState'
    ]),
    rowVxeClassHandler({ rowIndex }) {
      let className = ['light-row'];
      if (rowIndex % 2 === 1) className = ['light-row'];
      (this.activeIndex[1] || this.activeIndex[0]) === rowIndex
        ? className.push('active-row-c')
        : className.push('active-row-n');
      return className;
    },
    clickEvent(e, eItem) {
      this.setState({ key: 'eventDetailsVisible', payload: true });
      const currentRow = { event: { ...this.currentRow, ...eItem }, ...this.currentRow };
      localStorage.setItem('eRow', JSON.stringify(currentRow));
    },
    // 打印
    printerHandler(e, index) {
      if (+this.repTab === +index) {
        const rdoc = index === 1 ? document.querySelector('.fld-main-box .snapshot-data-s') : document.querySelector('.fld-main-box .snapshot-data-s2');
        e.stopPropagation();
        this.$nextTick(() => {
          this.$print(rdoc);
        });
      }
    },
    expandICon() {
      return <a-icon slot='suffixIcon' component={require('@/assets/icon/arrow-down-bold.svg')} />;
    },
    renderTMP(listData) {
      const iframe = document.getElementById('rep-iframe-fd');
      // 先插入将html中的document.write执行获得完整html
      iframe.contentWindow.document.write(this.repAnalysisJsonData);
      // 根据完整html过滤script
      const htmljson = toJSON(document.getElementById('rep-iframe-fd').contentWindow.document.body.innerHTML, { skipScript: true, skipStyle: true, pureClass: false, pureComment: true });

      this.tmpHtml = htmljson;
      this.headCode = document.getElementById('rep-iframe-fd').contentWindow.document.head.innerHTML;
      // // 将iframe中dom 更新为完成html
      iframe.contentWindow.document.open();
      iframe.contentWindow.document.write(toHTML(htmljson));
      iframe.contentWindow.document.close();

      this.htmlSourceCode = document.getElementById('rep-iframe-fd').contentWindow.document.body.innerHTML;
    },
    async changeTabHandler() {
      const { id, reportType, smi, version } = this.repShowData;
      let type = 1;
      switch (smi) {
        case 'DFD':
          type = 1;
          break;

        case 'ENG':
          type = 2;
          break;
      }
      const params = {
        repReportId: id,
        templateName: reportType,
        templateType: type,
        version
      };
      if (this.repId !== id) {
        await this.repAnalysisJson(params);
        this.renderTMP();
      }
      this.repId = id;
    },
    // 点击行
    customRow({ row, rowIndex }) {
      this.repId = -1;
      this.repShowData = { ...row };
      if (this.activeIndex[0] === rowIndex) {
        this.repShow = false;
        this.activeIndex[0] = [-1];
        document.querySelector('.left-menu').style.width = '37.5%';
        document.querySelector('.right-menu').style.width = '62.5%';
      } else {
        this.repShow = true;
        this.activeIndex = [rowIndex];
        this.repShowData.content = '\r\n' + row.content;
        if (this.repTab === '2') {
          if (this.repShowData.smi === 'CFD') {
            this.getFormattedMessage({ reportId: this.repShowData.id, imi: this.repShowData.imi });
          } else {
            this.changeTabHandler();
          }
        }
        this.$nextTick(() => {
          if (document.querySelector('.snapshot-data-s').scrollTop) {
            document.querySelector('.snapshot-data-s').scrollTop = 0;
            document.querySelector('.snapshot-data-s2').scrollTop = 0;
          }
        });
      }
      // const fldReportuuid = this.$route?.query?.fldReportuuid ?? new Date().getTime();
      // sessionStorage.setItem(`fldReportItem${fldReportuuid}`, JSON.stringify(row));
    },
    debounceRender: debounce(function(key) {
      setTimeout(() => {
        const fldh = document.querySelector('.fld-top-title').clientHeight;
        const t1 = `${document.body.clientHeight - 92 - fldh - 150}px`;
        // if (this.singlePage) {
        //   if (key.length === 0) {

        //   } else {
        //     t1 = 330;
        //   }
        // } else {
        //   if (key.length === 0) {
        //     t1 = 499;
        //   } else {
        //     t1 = 152;
        //   }
        // }

        this.vxeH = `${t1}px`;
      }, 190);
    }, 300),
    changeActiveHandler(key) {
      this.debounceRender(key);
    },
    // 当drawer点击关闭
    onClose() {
      this.$emit('close', 'flightLegDetailsVisible');
      this.activeIndex = [-1];
      this.repTab = '2';
      this.repId = -1;
    },
    async getData() {
      const { leg, tailnumber, id } = this.currentRow;
      await this.getFlightLegDetail({ leg, tailNumber: tailnumber, legId: id });
      this.reportTypes = [];
    },
    // 点击报告类型
    triggerHandler(name) {
      document.querySelector('.left-menu').style.width = null;
      this.repShow = false;
      this.activeIndex[0] = [-1];
      if (name === 'all') {
        this.reportTypes = [];
      } else {
        const index = this.reportTypes.indexOf(name);
        if (index > -1) {
          this.reportTypes.splice(index, 1);
        } else {
          this.reportTypes.push(name);
        }
      }

      if (this.reportTypes.length === this.flightLegDetailReportTypes.length) {
        this.reportTypes = [];
      }
      const params = {
        category: this.reportTypes.length > 0 ? this.reportTypes : this.flightLegDetailReportTypes.flatMap(item => item.name),
        tailNumber: this.currentRow.tailnumber,
        legId: this.currentRow.id
      };
      this.getRepReportS(params);
    },
    airportInfoHandler(code) {
      this.setState({ key: 'airportInfoVisible', payload: true });
      localStorage.setItem('apInfoCode', code);
    },
    goNewPageReportHandler() {
      const repShowDatauuid = new Date().getTime();
      sessionStorage.setItem(`repShowData${repShowDatauuid}`, JSON.stringify(this.repShowData));

      const routeData = this.$router.resolve({
        path: '/newPageReport',
        query: {
          repShowDatauuid
        }
      });

      window.open(routeData.href, '_blank');
    },
    goNewPageHandler(flduuid = '') {
      sessionStorage.setItem(`fld${flduuid}`, JSON.stringify(this.currentRow));

      const routeData = this.$router.resolve({
        path: '/reportsLayout',
        query: {
          rp: 'flightLegDetailsVisible',
          flduuid
        }
      });

      window.open(routeData.href, '_blank');
    }
  }
};
</script>

<style lang="less">
@import './index.less';
.legend-box {
  .b {
    display: flex;
    border: 1px solid #333;
    height: 250px;
    > div {
      border-right: 1px solid #333;
      display: flex;
      flex: 1;
      flex-direction: column;
      justify-content: space-between;
      align-items: flex-end;
      &:nth-last-child(1) {
        border-right: none;
      }
      .word {
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        writing-mode: vertical-lr; /*从左向右 从右向左是 writing-mode: vertical-rl;*/
        writing-mode: tb-lr;
        width: 100%;
      }
      .idx {
        background-color: #040404;
        height: 50px;
        line-height: 50px;
        width: 100%;
        text-align: center;
        color: #fff;
        flex-shrink: 0;
        position: relative;
        &.aa {
          background-color: #3e46ac;
        }
        .time {
          position: absolute;
          bottom: 40px;
          left: 3px;
          color: #333;
          writing-mode: vertical-lr;
          writing-mode: tb-lr;
          transform: rotate(-30deg);
        }
      }
    }
  }
}
</style>
